package com.ym.pms.interceptor;


import com.ym.pms.config.Constants;
import com.ym.pms.model.TokenModel;
import com.ym.pms.service.TokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: xybh
 * @Description:
 * @Date: Created in 22:04 2020/12/16
 * @Modified:
 */
public class AuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private TokenManager manager;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //从header中得到token
        String authorization = request.getHeader(Constants.AUTHORIZATION);
        //验证token
        TokenModel model = manager.getToken(authorization);
        if (manager.checkToken(model)) {
            //如果token验证成功，将token对应的用户id存在request中，便于之后注入
            model.getUserId();
            request.setAttribute(Constants.CURRENT_USER_ID, model.getUserId());
        }
    }
}
